layui.jquery(function(){
  var $ = layui.jquery
      ,layer = layui.layer
      ,laydate = layui.laydate
      ,laypage = layui.laypage
      ,upload = layui.upload
      ,form = layui.form;
  window.layer = layer;
  app.show = function(dom){
    if (dom != '#login' && dom != '#register') {
      $("#main").show().siblings().hide();
    }
    $(dom).show().siblings().hide();
  }
  app.ajax = function (x) {
    $.ajax({
      url: app.host + '/diagnostic' + x.url, type: x.type, xhrFields: { withCredentials: true }, crossDomain: true, dataType: 'json',
      data: x.data, success: x.sucFun
    });
  }
  app.initFn = function(){
    // 将gid, cid转换为对应的grade和course
    app.chgGidCid = function (t) {
      for (var i = 0; i < app.courses.length; i++) {
        if (app.courses[i].id == t.c_id) {
          t.course = app.courses[i].course;
          break;
        }
      }
      for (var i = 0; i < app.grades.length; i++) {
        if (app.grades[i].id == t.g_id) {
          t.grade = app.grades[i].grade;
          break;
        }
      }
      return t;
    };
    app.ajax({url: '/admin/islogin', type: 'GET', sucFun: function (rst) {
      $("body > .content").show();
      if (rst.login_status == 0) {
        app.initLogin();
      } else {
        app.adminStatus = rst.login_status;
        app.adminName = rst.admin_name;
        app.adminId = rst.admin_id;
        if (rst.login_status == 1) {
          app.initTaskList();
        } else if (rst.login_status == 2) {
          app.initTeacherList();
          $("#taskMenu").show();
        }
      }
      if (rst.login_status != 0) {
        $('.logout').click(function () {
          var layerId = layer.confirm('确认退出登录？', {
            btn: ['确定','取消']
          }, function(){
            layer.close(layerId);
            app.ajax({url: '/Admin/logout', type: 'GET', sucFun: function (rst) {
              // app.show("#login");
              location.reload();
            }});
          });
        });
      }
    }});
    app.ajax({url: '/grade/getGrades', type: 'GET', sucFun: function (rst) {
      app.grades = rst.gradeInfos;
      var _h = [];
      for (var i = 0; i < app.grades.length; i++) {
        _h.push('<option value="' + app.grades[i].id + '">' + app.grades[i].grade + '</option>');
      }
      // app.gradesHtml = _h.join("");
      $('.gradeSelect').append(_h.join(""));
      form.render('select');
    }});
    app.ajax({url: '/course/getCourses', type: 'GET', sucFun: function (rst) {
      app.courses = rst.courseInfos;
      var _h = [];
      for (var i = 0; i < app.courses.length; i++) {
        _h.push('<option value="' + app.courses[i].id + '">' + app.courses[i].course + '</option>');
      }
      // app.coursesHtml = _h.join("");
      $('.courseSelect').append(_h.join(""));
      form.render('select');
    }});
  };
  app.initTaskList = function () {
    app.initedTaskList = 1;
    app.show('#taskList');
    app.getTaskData = {};
    laydate.render({ elem: '#date', range: '~', done: function(value, date, endDate){
      var date = value.split(' ~ ');
      if (value != "") {
        app.getTaskData.s_time = date[0];
        app.getTaskData.e_time = date[1];
      } else {
        delete app.getTaskData.s_time;
        delete app.getTaskData.e_time;
      }
    }});
    laydate.render({ elem: '#cdate', range: '~', done: function(value, date, endDate){
      var date = value.split(' ~ ');
      if (value != "") {
        app.getTaskData.start_time = date[0];
        app.getTaskData.end_time = date[1];
      } else {
        delete app.getTaskData.start_time;
        delete app.getTaskData.end_time;
      }
    }});
    $('#filterTask').click(function () {
      var t = {page: 1},
          kw = $("#taskList [name=name]").val(),
          c_id = $("#taskList [name=course]").val(),
          g_id = $("#taskList [name=grade]").val(),
          status = $("#taskList [name=status]").val();
      kw ? t.keywords = kw : '';
      c_id ? t.c_id = c_id : '';
      g_id ? t.g_id = g_id : '';
      status ? t.status = status : '';
      app.getTaskData = t;
      app.getTaskList();
    });
    $('#taskList').delegate('.getTask', 'click', function () {
      var _this = $(this).parent(), id = _this.attr('data-id');
      var layerId = layer.confirm('确认领取？', {
        btn: ['确定','取消']
      }, function(){
        layer.close(layerId);
        app.ajax({url: '/Signupinfo/receive', data: {id: id}, type: 'POST', sucFun: function (rst) {
          if (rst.code == 1000) {
            _this.html('<a class="editTask layui-btn layui-btn-small">编辑</a>');
          } else {
            layer.msg(rst.message);
          }
        }});
      });
    });
    $('#taskList').delegate('.editTask', 'click', function () {
      var _this = $(this).parent(), o = JSON.parse(_this.attr('data-obj'));
      app.ajax({url: '/Signupinfo/getOneEvaluation', data: {s_id: o.id}, type: 'GET', sucFun: function (rst) {
        if (rst.code == 1000) { // 测评信息存在则需要填入, 不存在则无需处理
          app.taskRst = rst.evaluationInfo;
          $('#taskDetail [name=content]').val(app.taskRst.content).removeAttr("disabled");
          $('#taskDetail [name=paper]').val(app.taskRst.paper);
          $("#rstFile").show();
        } else {
          app.taskRst = {s_id: o.id};
        }
      }});

      app.show('#taskDetail');
      $('#taskDetail [name=name]').val(o.name);
      $('#taskDetail [name=phone]').val(o.phone);
      $('#taskDetail [name=qq]').val(o.qq);
      $('#taskDetail [name=grade]').val(o.grade);
      $('#taskDetail [name=course]').val(o.course);
      $('#taskDetail [name=date]').val(o.date);

      app.initTaskDetail();
    });
    $('#taskList').delegate('.showTask', 'click', function () {
      var _this = $(this).parent(), o = JSON.parse(_this.attr('data-obj'));
      app.ajax({url: '/Signupinfo/getOneEvaluation', data: {s_id: o.id}, type: 'GET', sucFun: function (rst) {
        if (rst.code == 1000) { // 测评信息存在则需要填入, 不存在则无需处理
          app.taskRst = rst.evaluationInfo;
          $('#taskDetail [name=content]').val(app.taskRst.content).attr("disabled",'disabled');
          $('#taskDetail [name=paper]').val(app.taskRst.paper);
          $("#rstFile").hide();
        } else {
          app.taskRst = {s_id: o.id};
        }
      }});

      app.show('#taskDetail');
      $('#taskDetail [name=name]').val(o.name);
      $('#taskDetail [name=phone]').val(o.phone);
      $('#taskDetail [name=qq]').val(o.qq);
      $('#taskDetail [name=grade]').val(o.grade);
      $('#taskDetail [name=course]').val(o.course);
      $('#taskDetail [name=date]').val(o.date);

      app.initTaskDetail();
    });
    app.initTaskDetail = function () {
      if (!app.initedTaskDetail) {
        app.initedTaskDetail = 1;
        upload.render({
          elem: '#rstFile'
          ,url: app.host + '/diagnostic/Common/uploadFile' //必填项
          ,data: {exts: '["docx","doc"]'} //可选项。额外的参数，如：{id: 123, abc: 'xxx'}
          ,accept: 'file' //允许上传的文件类型
          ,exts: 'docx|doc'
          ,done: function(res, index, upload){ //上传后的回调
            if (res.code == '1000') {
              layer.msg('上传成功!');
              app.taskRst.paper = res.src;
              $('#taskDetail [name=paper]').val(res.src);
            } else {
              layer.msg(res.message);
            }
          }
        });

        $('.toTaskList').click(function () {
          app.show('#taskList');
        });

        $('#saveTask').click(function () {
          var content = $('#taskDetail [name=content]').val();
          if (content != '') {
            app.ajax({url: '/Signupinfo/saveSignupInfo', data: {
              id: app.taskRst.s_id
              , paper: app.taskRst.paper ? app.taskRst.paper : ''
              , content: content, status: 3
            }
            , type: 'POST', sucFun: function (rst) {
              if (rst.code == 1000) {
                layer.msg('保存成功');
                app.getTaskList();
                app.show('#taskList');
              } else {
                layer.msg(rst.message);
              }
            }});
          } else {
            layer.msg('诊断结果不能为空');
          }

        });
      }
    };
    app.getTaskList = function () {
        app.ajax({url: '/Signupinfo/getSignupInfos', data: app.getTaskData, type: 'GET', sucFun: function (rst) {
          app.tasks = rst.signupInfos;
          app.renderPage('taskListPage', rst.count, rst.limit, function(obj){
            app.getTaskData.page = obj.curr;
            app.getTaskList();
          });
          var _h = [];
          for (var i = 0; i < app.tasks.length; i++) {
            var t = app.chgGidCid(app.tasks[i]),
                operateBtn = t.status == 1 ?
                  '<a class="getTask layui-btn layui-btn-small">领取</a>' :
                  (app.adminId==t.t_id?'<a class="editTask layui-btn layui-btn-small">编辑</a>':
                    (app.adminStatus==2?'<a class="showTask layui-btn layui-btn-small">查看</a>':'')),
                status = t.status == 1 ? '未领取' : (t.status == 2 ? '已领取' : '已完成');
            t.date = app.getTimeRange(Number(t.start_time+'000'),Number(t.end_time+'000'));
            _h.push('<tr><th>'+t.name+'</th><th>'+t.grade+'</th><th>'+t.course+'</th><th>'+app.getTime(Number(t.signup_time+'000'))
                    + '</th><th>'+ t.date
                    + '</th><th>' + status
                    + '</th><th>' + t.t_name + '</th>'
                    + '<th data-id="' + t.id +'" data-obj=' + "'" + JSON.stringify(t) + "'" + '>' + operateBtn + '</th></tr>');
          }

          $('#taskList tbody').html('').append(_h.join(""));
          // form.render('select');
        }});
    };
    app.getTaskList();
  };
  app.initEditLesson = function (obj) {
    app.editLessonData = obj;
    laydate.render({ elem: '#lessonTime', range: '~', format: 'yyyy-MM-dd HH:mm', type: 'datetime'
      ,value: app.getDateTimeRange(Number(obj.start_time+'000'), Number(obj.end_time+'000'))
      ,done: function(value, date, endDate){
        var date = value.split(' ~ ');
        app.editLessonData.start_time = (new Date(date[0])).getTime()/1000;
        app.editLessonData.end_time = (new Date(date[1])).getTime()/1000;
    }});
    $("#editLesson [name=number]").val(obj.number);
    $("#editLesson [name=course]").val(obj.c_id);
    $("#editLesson [name=grade]").val(obj.g_id);
    app.ajax({url: '/Admin/getOneTeacher', type: 'GET', data: {id: obj.t_id}, sucFun: function (rst) {
      var t = rst.teacherInfo;
      $('#editLesson [name=teacher]').append('<option value="' + t.id + '" selected>' + t.realname + '</option>');
      form.render('select');
    }});


    if (!app.initedEditLesson) {
      $('#saveLesson').click(function () {
        app.editLessonData.number = $("#editLesson [name=number]").val();
        app.editLessonData.c_id = $("#editLesson [name=course]").val();
        app.editLessonData.g_id = $("#editLesson [name=grade]").val();
        app.editLessonData.t_id = $("#editLesson [name=teacher]").val();
        app.editLessonData.name = $("#editLesson [name=teacher]").find('[value='+app.editLessonData.t_id+']').text();
        app.ajax({url: '/Classinfo/saveClass', data: app.editLessonData, type: 'POST', sucFun: function (rst) {
          if (rst.code == 1000) {
            layer.msg('保存成功');
            app.getLessonList();
            app.show('#lessonList');
          } else {
            layer.msg(rst.message);
          }
        }});
      });
      $('.searchTeacher').click(function () {
        var dom = $('#editLesson [name=teacher]'), kw = dom.next().find('input').val();
        app.getTeachersList({keywords: kw}, function () {
          var _h = [];
          for (var i = 0; i < app.teachers.length; i++) {
            _h.push('<option value="' + app.teachers[i].id + '">' + app.teachers[i].realname + '</option>');
          }
          dom.append(_h.join(''));
        });
      });
    }
  };
  app.initLessonList = function () {
    app.show('#lessonList');
    app.initedLessonList = 1;
    app.getLessonData = {};
    $('.toTeacherList').click(function () {
      app.show('#teacherList');
    });
    laydate.render({ elem: '#lessonDate', range: '~', done: function(value, date, endDate){
      var date = value.split(' ~ ');
      if (value != "") {
        app.getLessonData.start_time = date[0];
        app.getLessonData.end_time = date[1];
      } else {
        delete app.getLessonData.start_time;
        delete app.getLessonData.end_time;
      }
    }});

    $('#lessonList').delegate('.editLesson', 'click', function () {
      var obj = $(this).parent().attr('data-obj');

      app.initEditLesson(JSON.parse(obj));
      app.show('#editLesson');
    });
    $('#lessonList').delegate('.deleteLesson', 'click', function () {
      var _this = $(this).parent(), id = _this.attr('data-id');
      var layerId = layer.confirm('确认删除？', {
        btn: ['确定','取消']
      }, function(){
        layer.close(layerId);
        app.ajax({url: '/Classinfo/deleteClass', data: {id: id}, type: 'POST', sucFun: function (rst) {
          if (rst.code == 1000) {
            layer.msg('删除成功');
            _this.parent().remove();
          } else {
            layer.msg(rst.message);
          }
        }});
      });
    });

    $('#filterLesson').click(function () {
      var t = {page: 1}
          ,kw = $('#lessonList [name=keywords]').val()
          ,g_id = $('#lessonList [name=grade]').val()
          ,c_id = $('#lessonList [name=course]').val()
          ,status = $('#lessonList [name=status]').val();
      kw ? t.keywords = kw : '';
      status ? t.status = status : '';
      g_id ? t.g_id = g_id : '';
      c_id ? t.c_id = c_id : '';
      if (app.getLessonData.start_time) {
        t.start_time = app.getLessonData.start_time;
        t.end_time = app.getLessonData.end_time;
      }
      app.getLessonData = t;
      app.getLessonList();
    });
    $("#downloadExcel").click(function () {
      location.href = 'http://cdn.gzpeiyou.com/single/js/diagnostic/在线诊断管理员模板.xls';
    });
    upload.render({
      elem: '#lessonImport'
      ,url: app.host + '/diagnostic/Common/uploadFile' //必填项
      ,data: {exts: '["xlsx","xls","csv"]'} //可选项。额外的参数，如：{id: 123, abc: 'xxx'}
      ,accept: 'file' //允许上传的文件类型
      ,exts: 'xlsx|xls|csv'
      ,done: function(res, index, upload){ //上传后的回调
        if (res.code == '1000') {
          app.ajax({url: '/Classinfo/addClassByExcel', data: {excel: res.src}, type: 'POST', sucFun: function (rst) {
            layer.msg(rst.message);
            app.getLessonList();
          }});
        }
      }
    });

    app.getLessonList = function () {
      app.ajax({url: '/Classinfo/getClasses', data: app.getLessonData, type: 'GET', sucFun: function (rst) {
        app.classes = rst.classInfos;
        app.renderPage('lessonListPage', rst.count, rst.limit, function(obj){
          app.getLessonData.page = obj.curr;
          app.getLessonList();
        });
        var _h = [];
        for (var i = 0; i < app.classes.length; i++) {
          var t = app.chgGidCid(app.classes[i]),
              operateBtn = t.status == 1 ? '<a class="editLesson layui-btn layui-btn-small">编辑</a><a class="deleteLesson layui-btn layui-btn-small">删除</a>' : '';

          _h.push('<tr><th>' + t.name + '</th><th>' + app.getTimeRange(Number(t.start_time+'000'),Number(t.end_time+'000')) +'</th><th>' + t.grade
                  + '</th><th>' + t.course + '</th><th>' + t.number + ' | ' + t.signup_number + '</th>'
                  + '<th data-id="' + t.id +'" data-obj=' + "'" + JSON.stringify(t) + "'" + '>' + operateBtn + '</th></tr>');
        }
        $('#lessonList tbody').html('').append(_h.join(""));
        form.render('select');
      }});
    };
    app.getLessonList();
  };


  app.initTeacherList = function () {
    app.show('#teacherList');
    $('.toLessonList').click(function () {
      if (!app.initedLessonList) {
        app.initLessonList();
      }
      app.show('#lessonList');
    });
    $('.toTaskList').click(function () {
      if (!app.initedTaskList) {
        app.initTaskList();
      }
      app.show('#taskList');
    });

    var examine = function (data, fn) {
      app.ajax({url: '/Admin/examineTeacher', type: 'POST', data: data, sucFun: function (rst) {
        if (rst.code == 1000 || rst.code == 1002) {
          fn();
        } else {
          layer.msg(rst.message);
        }
      }});
    }
    $('#teacherList').delegate('.passBtn', 'click', function () {
      var _this = $(this).parent(), id = _this.attr('data-id');
      var layerId = layer.confirm('确认通过？', {
        btn: ['确定','取消']
      }, function(){
        layer.close(layerId);
        examine({id:id, status:2}, function () {
          _this.html('').prev().text('已通过');
        });
      });
    });
    $('#teacherList').delegate('.refuseBtn', 'click', function () {
      var _this = $(this).parent(), id = _this.attr('data-id');
      var layerId = layer.confirm('确认不通过？', {
        btn: ['确定','取消']
      }, function(){
        layer.close(layerId);
        examine({id:id, status:3}, function () {
          _this.parent().remove();
        });
      });
    });
    $('#teacherList').delegate('.deleteBtn', 'click', function () {
      var _this = $(this).parent(), id = _this.attr('data-id');
      var layerId = layer.confirm('删除后只能重新注册恢复，确认删除？', {
        btn: ['确定','取消']
      }, function(){
        layer.close(layerId);
        app.ajax({url: '/Admin/deleteTeacher', type: 'POST', data: {'id':id}, sucFun: function (rst) {
          if (rst.code == 1000 || rst.code == 1002) {
            _this.parent().remove();
          } else {
            layer.msg(rst.message);
          }
        }});
      });
    });

    $('#filterTeacher').click(function () {
      var t = {page: 1}
          ,kw = $('#teacherList [name=keywords]').val()
          ,g_id = $('#teacherList [name=grade]').val()
          ,c_id = $('#teacherList [name=course]').val()
          ,status = $('#teacherList [name=status]').val();
      kw ? t.keywords = kw : '';
      status ? t.status = status : '';
      g_id ? t.g_id = g_id : '';
      c_id ? t.c_id = c_id : '';
      app.getTeachersData = t;
      app.getTeachersList();
    });
    // 获取教师信息列表
    app.getTeachersData = {};
    app.getTeachersList = function (data, fn) {
      var _f = true;
      if (!data) {
        _f = false;
        data = app.getTeachersData;
      }
      app.ajax({url: '/Admin/getTeachers', data: data, type: 'GET', sucFun: function (rst) {
        app.teachers = rst.teacherInfos;
        if (!_f) {
          app.renderPage('teacherListPage', rst.count, rst.limit, function(obj){
            app.getTeachersData.page = obj.curr;
            app.getTeachersList();
          });
          var _h = [];
          for (var i = 0; i < app.teachers.length; i++) {
            var t = app.chgGidCid(app.teachers[i]), status = t.status == 1 ? '待审核' : (t.status == 2 ? '已通过' : '已拒绝'),
                operateBtn = t.status == 1 ? '<a class="passBtn layui-btn layui-btn-small">通过</a><a class="refuseBtn layui-btn layui-btn-small">不通过</a>' : '<a class="deleteBtn layui-btn layui-btn-small">删除</a>';

            _h.push('<tr><th>' + t.realname +'</th><th>' + t.username + '</th><th>' + t.grade + '</th><th>' + t.course + '</th><th>' + status + '</th>'
                    + '<th data-id="' + t.id + '">' + operateBtn + '</th></tr>');
          }
          $('#teacherList tbody').html('').append(_h.join(""));
        } else {
          fn();
        }
        form.render('select');
      }});
    };
    app.getTeachersList();
  };

  app.renderPage = function (id, count, limit, fn) {
    laypage.render({
      elem: id //注意，这里的 test1 是 ID，不用加 # 号
      ,count: count //数据总数，从服务端得到
      ,limit: limit
      ,jump: function(obj, first){
        //首次不执行
        if(!first){
          fn(obj);
        }
      }
    });
  }
  app.initRegister = function () {
    app.registerInited = 1;
    $('#toLogin').click(function () {
      app.show("#login")
    });
    $('#getCode').click(function () {
      var phone = $('#register [name=phone]').val();
      if (/^1[0-9]{10}$/.test(phone)) {
        layer.open({type:3});

        $.ajax({
          url: app.host + '/Lecture/Datas/sms', type: 'POST', xhrFields: { withCredentials: true }, crossDomain: true,
          data:{
            phone: phone
          },
          type:'POST', dataType: 'json',
          success: function(rst){
            layer.closeAll('loading');
            if(rst && rst.code){
              layer.msg("验证码发送成功");
              app.code = rst.code;
              app.phone = phone;
              app.time = 60;
              $('#getCode').hide().next().show();
              app.intervalId = setInterval(function () {
                if (app.time == 0) {
                  $('#second i').text('60').parent().hide().prev().show();
                  clearInterval(app.intervalId);
                }else {
                  $('#second i').text(--app.time);
                }
              }, 990);
            }else {
              layer.msg("发送失败,<br/>请稍后再试");
            }
          }
        });
      }else {
        layer.msg("请输入正确的手机号码");
      }
    });

    $('#confirmRegister').click(function () {
      var data = {
        username: app.phone,
        phone: app.phone,
        password: $('#register [name=password]').val(),
        realname: $('#register [name=realname]').val(),
        g_id: $('#register [name=grade]').val(),
        c_id: $('#register [name=course]').val()
      }, code = $('#register [name=code]').val();
      if (code != app.code) {
        layer.msg("验证码不正确");
      } else if (data.password.length<6) {
        layer.msg("请输入6位以上的密码");
      } else if (data.realname.length<2) {
        layer.msg("请输入您的真实姓名");
      } else if (!data.g_id) {
        layer.msg("请选择年级");
      } else if (!data.c_id) {
        layer.msg("请选择科目");
      } else {
        app.ajax({url: '/Admin/saveTeacher', type: 'GET', data: data, sucFun: function (rst) {
          if (rst.code == 1000) {
            layer.msg('注册成功');
            app.show("#login");
          } else {
            layer.msg(rst.message);
          }
        }});
      }
    });
  };
  app.initLogin = function () {
    app.show("#login");
    $('#toRegister').click(function () {
      if (!app.registerInited) {
        app.initRegister();
      }
      app.show("#register");
    });
    $('#confirmLogin').click(function () {
      var data = {
        username: $('#login [name=phone]').val(),
        password: $('#login [name=password]').val()
      };
      // if (/^1[0-9]{10}$/.test(data.username)) {
        app.ajax({url: '/admin/login', type: 'POST', data: data, sucFun: function (rst) {
          if (rst.code == 1000) {
            location.reload();
          }else {
            layer.msg(rst.message);
          }
        }});
      // }else {
      //   layer.msg('请输入正确的手机号码');
      // }
    });
  }
});

try {

  app.initFn();

} catch (e) {
  console.log(e);
} finally {

}
